var express = require("express");
var router = express.Router();

const conn = require("../mysql/index.js");
router.get("/list", async function (req, res, next) {
  let page = parseInt(req.query.page || 1);
  let size = parseInt(req.query.size || 10);
  let total = 0;
  try {
    conn.query("SELECT COUNT(*) AS total FROM users", (error, results) => {
      if (error) {
        res.send({
          code: 400,
          msg: error,
        });
        return;
      }
      total = results[0].total;
    });
    conn.query(
      "SELECT * FROM users LIMIT ? OFFSET ?",
      [size, parseInt((page - 1) * size)],
      (error, results) => {
        if (error) {
          res.send({
            code: 400,
            msg: error,
          });
          return;
        }
        res.send({
          code: 200,
          data: results,
          page: page,
          size: size,
          total: total,
        });
      }
    );
  } catch (e) {
    res.send({
      code: 400,
      msg: "查询失败",
    });
  }
});
router.post("/add", async function (req, res, next) {
  let { username, password } = req.body;
  console.log(username, password);
  try {
    conn.query(
      "INSERT INTO users (username, password) VALUES (?, ?)",
      [username, password],
      (error, results) => {
        if (error) {
          res.send({
            code: 400,
            msg: error,
          });
          return;
        }
        res.send({
          code: 200,
          msg: "添加成功",
        });
      }
    );
  } catch (e) {
    res.send({
      code: 400,
      msg: "添加失败",
    });
  }
});
module.exports = router;
